{extend name="layout/layout" /}
<!--请在下方写此页面body相关内容-->
{block name="container"}
<div id="app" v-cloak>
    <div class="panel-main">
        <div class="main-search">111</div>
        <div class="main-header">
            <el-button type="info" size="mini" plain title="刷新列表" @click="refresh"><i class="el-icon-refresh"></i></el-button>
            <el-button type="primary" size="mini" plain title="新增" @click="refresh"><i class="el-icon-plus"></i>新增</el-button>
            <el-input placeholder="快速搜索"
                      suffix-icon="el-icon-search"
                      size="mini"
                      clearable
                      v-model="searchParam"
                      @clear="getList"
                      @keyup.native="getList">
            </el-input>
        </div>
        <div class="main-body">
            <el-table :data="list"
                    v-loading="loading"
                    row-key="id"
                    :expand-row-keys="expands"
                    @row-click="rowClick"
                    :default-sort="defaultSort"
                    @sort-change="handleSortChange"
                    :highlight-current-row="highlightCurrentRow">
                <el-table-column type="expand">
                    <template slot-scope="props">
                        <el-form label-position="left" inline class="demo-table-expand">
                            <el-form-item label="用户名">
                                <span>{{ props.row.username }}</span>
                            </el-form-item>
                            <el-form-item label="用户ID">
                                <span>{{ props.row.id }}</span>
                            </el-form-item>
                            <el-form-item label="用户组">
                                <el-cascader
                                        :disabled="groupDisabled"
                                        placeholder="快速搜索"
                                        :options="groupList"
                                        filterable
                                        change-on-select
                                        size="mini"
                                        separator="/"
                                        v-model="props.row.selected_group"
                                        @change="groupChange"
                                ></el-cascader>
                            </el-form-item>
                            <el-form-item label="状态">
                                <el-button v-if="props.row.status == 1" type="success" size="mini" plain disabled>正常</el-button>
                                <el-button v-else-if="props.row.status == 2" type="danger" size="mini" plain disabled>禁用</el-button>
                                <el-button v-else-if="props.row.status == 3" type="info" size="mini" plain disabled>删除</el-button>
                            </el-form-item>
                            <el-form-item label="登录时间" :formatter="format(props.row.last_login_time)">
                                <span>{{ format(props.row.last_login_time) }}</span>
                            </el-form-item>
                            <el-form-item label="登录IP">
                                <span>{{ props.row.last_login_ip }}</span>
                            </el-form-item>
                            <el-form-item label="创建时间" :formatter="format(props.row.create_time)">
                                <span>{{ format(props.row.create_time) }}</span>
                            </el-form-item>
                            <el-form-item label="更新时间" :formatter="format(props.row.update_time)">
                                <span>{{ format(props.row.update_time) }}</span>
                            </el-form-item>
                            <el-form-item lable="" class="opt">
                                <el-button class="ml-20" type="primary" size="mini" plain @Click="onSave(props.row)"><i class="el-icon-third-submit"></i>保存</el-button>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column
                        label="ID"
                        min-width="60"
                        sortable="custom"
                        prop="id">
                </el-table-column>
                <el-table-column
                        label="用户名"
                        min-width="120"
                        prop="username">
                </el-table-column>
                <el-table-column
                        label="用户组"
                        min-width="150"
                        prop="group_name">
                </el-table-column>
                <el-table-column
                        label="状态"
                        min-width="80"
                        prop="status">
                    <template slot-scope="scope">
                        <el-button v-if="scope.row.status == 1" type="success" size="mini" plain @click.native.prevent="setStatus(scope.$index, list, 2)">正常</el-button>
                        <el-button v-else-if="scope.row.status == 2" type="danger" size="mini" plain @click.native.prevent="setStatus(scope.$index, list, 1)">禁用</el-button>
                        <el-button v-else-if="scope.row.status == 3" type="info" size="mini" plain>删除</el-button>
                    </template>
                </el-table-column>
                <el-table-column
                        label="操作"
                        fixed="right"
                        width="100">
                    <template slot-scope="scope">
                        <el-button size="mini" title="重置密码" type="text" @click="resetPassword(scope.row.id)"><i class="el-icon-third-repwd"></i></el-button>
                        <el-button size="mini" title="删除" type="text" @click.native.prevent="delRow(scope.$index, list)"><i class="el-icon-delete"></i></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</div>

{/block}
<!--请在上方方写此页面body相关内容-->

<!--请在下方写此页面业务相关的脚本-->
{block name="js"}
<script>
var vm = new Vue({
    el: '#app',
    data: {
        list: [],
        loading: true,
        activeName: 'list',
        searchParam: '',
        defaultSort: {
            prop: 'id',
            order: 'descending'
        },
        expands: [],    // 要展开的行，数值的元素是row的key值
        expandsRow: [],    // 拖动关闭展开行时记录展开的行号
        highlightCurrentRow: true,
        groupList: [],
        groupDisabled: false,
        form: {
            id: '',
            username: '',
            group_id: ''
        }
    },
    methods: {
        getList(column) {
            let _this = this;

            if (column && column.prop && column.order) {
                _this.defaultSort.prop = column.prop;
                _this.defaultSort.order = column.order;
            }

            $.ajax({
                url: 'adminList',
                type: 'post',
                data: {
                    sort_filed: _this.defaultSort.prop,
                    sort_order: _this.defaultSort.order,
                    search_name: _this.searchParam ? $.trim(_this.searchParam ) : '',
                },
                beforeSend: function(){
                    _this.loading = true;
                },
                success: function (res) {
                    if (res.code !== 0) {
                        _this.$message.error(res.msg);
                        return;
                    }
                    setTimeout(() => {
                        _this.list = res.data;
                        _this.loading = false;
                    }, 200 * Math.random());
                },
                error: function () {
                    _this.loading = false;
                }
            });
        },
        getGroup() {
            $.ajax({
                url: 'groupList',
                type: 'post',
                data: {},
                success: function (res) {
                    if (res.code !== 0) {
                        vm.$message.error(res.msg);
                        return;
                    }
                    vm.groupList = res.data;
                }
            });
        },
        rowClick(row, event, column) {  // 在<table>里，我们已经设置row的key值设置为每行数据id：row-key="id"
            let elem = event.target;

            while (elem) {  //循环判断至跟节点，防止点击的是子元素
                if (elem && elem.type === 'button') {
                    return;
                }
                elem = elem.parentNode;
            }
            Array.prototype.remove = function (val) {
                let index = this.indexOf(val);
                if (index > -1) {
                    this.splice(index, 1);
                }
            };
            if (this.expands.indexOf(row.id) < 0) {
                this.expands = []; // 单行展开，注释则多行
                this.expands.push(row.id);
                this.expands.sort();
                this.highlightCurrentRow = true;
            } else {
                this.expands.remove(row.id);
                this.highlightCurrentRow = false;
            }
        },
        rowDrop() {  // 拖动行
            const tbody = document.querySelector('.el-table__body-wrapper tbody');
            const _this = this;

            Sortable.create(tbody, {
                // 选取元素时触发
                onChoose: function(e) {
                    // console.log(e);
                },
                // 开始拖动元素时触发,可以获取到开始时的位置
                onStart: function (e) {
                    _this.expandsRow = _this.expands;
                    _this.expands = [];  // 拖动时关闭展开行
                },
                // 拖动结束时触发,可以获取到结束时的新位置
                onEnd(e) {
                    //如果拖动位置不变不作处理，展开原行
                    if (e.newIndex === e.oldIndex) {
                        _this.expands = _this.expandsRow;
                        return;
                    }
                    // 当每有一个展开行时行号会自动+1，暂支持1行展开
                    if (_this.expandsRow.length > 0) {
                        // 当展开行在小行号上，从大行号拖到小行号，需要减去展开行数
                        if (e.oldIndex - 1 > e.newIndex) {
                            e.oldIndex--;
                        }
                    }

                    const newRow  = _this.list[e.newIndex];
                    const currRow = _this.list.splice(e.oldIndex, 1)[0];
                    _this.list.splice(e.newIndex, 0, currRow);

                    // 不知道为什么加了fixed固定列，拖动结束后固定列上还有鼠标滑过样式，索性去掉
                    $('.el-table__fixed-body-wrapper tbody tr').removeClass('hover-row');

                    $.ajax({
                        url: 'sort',
                        type: 'post',
                        data: {
                            id: newRow.id+","+currRow.id
                        },
                        beforeSend: function(){
                            _this.loading = true;
                        },
                        success: function (res) {
                            if (res.code !== 0) {
                                _this.$message.error(res.msg);
                            }
                            setTimeout(() => {
                                _this.expands = _this.expandsRow;
                                _this.loading = false;
                            }, 200 * Math.random());
                        }
                    });
                },
            })
        },
        delRow(index, list) {
            const url = 'del';
            del(this, index, list, url); // 删除-公共函数
        },
        setStatus(index, list, val) {
            const url = 'status';
            status(this, index, list, url, val); // 修改状态-公共函数
        },
        resetPassword(id) {
            let _this = this;
            this.$confirm('确认重置密码吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                $.ajax({
                    url: 'resetPassword',
                    type: 'post',
                    data: {
                        id: id
                    },
                    beforeSend: function(){
                        _this.loading = true;
                    },
                    success: function (res) {
                        if (res.code !== 0) {
                            _this.$message.error(res.msg);
                        }
                        setTimeout(() => {
                            _this.loading = false;
                            _this.$message.success('已重置!');
                        }, 200 * Math.random());
                    }
                });
            }).catch(() => {
                _this.$message.info('已取消!');
            });
        },
        groupChange(val) {
            const group_arr = [];
            $.each(val, function (k,v) {
                group_arr.push(v);
            });
            // 取最后一级id作为选择id
            vm.form.group_id = group_arr.pop();
        },
        onSave(row) {
            let _this = this;

            // 目前就一个可以修改的，所以直接判断
            if (vm.form.group_id === '' || row.group_id === vm.form.group_id) {
                _this.$message.success('操作成功');
                return;
            }
            vm.form.id = row.id;
            vm.form.username = row.username;

            $.ajax({
                url: 'adminSave',
                type: 'post',
                data: vm.form,
                beforeSend: function(){
                    _this.loading = true;
                },
                success: function (res) {
                    if (res.code !== 0) {
                        _this.$message.error(res.msg);
                    }
                    setTimeout(() => {
                        _this.loading = false;
                        _this.$message.success('操作成功');
                    }, 200 * Math.random());
                },
                error: function () {
                    _this.loading = false;
                }
            });
        },
        handleSortChange(column) {
            this.getList(column);
        },
        refresh() {
            this.getList();
            this.expands = [];  // 关闭展开行
        },
        format(timestamp){ // 格式化时间
            return formatDate(timestamp);
        }
    },
    mounted() {
        this.rowDrop();  // 拖动行
        this.getGroup();  // 获取用户组列表
    }
});
</script>
{/block}
<!--/请在上方写此页面业务相关的脚本-->